package com.feimt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feimt.common.CodeUtils;
import com.feimt.common.SMSSendCode;
import com.feimt.pojo.User;
import com.feimt.result.R;
import com.feimt.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 宋孟林
 * @description
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    private  UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 生成验证码，将验证码存入会话，调用alibaba发送短信
     * @return 返回信息给前端
     */
    @PostMapping("/sendMsg")
    public R<Object> sendMsg(@RequestBody User user, HttpSession session){
        //session 对象在springboot中的mvc开发中会实例化session这个对象
        log.info("当前登录用户为： {}" , user);
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = CodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);
            try {
                SMSSendCode.sendCode(phone, code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            session.setAttribute(phone, code);
            return R.success(code);
        }
        return R.error("短信发送失败");
    }

    /**
     * 用户端登录程序，使用map，session作为参数，spring会将json数据转换为map的键值对，session可以保存键值对
     * @param map json数据
     * @param session key value
     * @return 返回前端数据显示
     */
    @PostMapping("/login")
    public R<Object> login(@RequestBody Map<String, String> map, HttpSession session){
        log.info("map info:{}", map);
        String phone = map.get("phone");
        String code = map.get("code");
        String sessionCode = (String) session.getAttribute(phone);
        if (code == null || !code.equals(sessionCode)){
            return R.error("手机号或验证码有误");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userService.getOne(wrapper);
        if (user == null){
            User user1 = new User();
            user1.setPhone(phone);
            user1.setName(phone);
            userService.save(user1);
            session.setAttribute("user", user1.getId());
            return R.success(user1);
        }else {
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
    }

    @PostMapping("/loginout")
    public R<String> login0ut(HttpServletRequest request){
        log.info("用户退出");
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

    /**
     * 修改用户的信息，如果修改成功则返回新的user对象，失败返回null
     * @param user 提交的user信息
     * @return 返回新的user1对象
     */
    @PutMapping("/update")
    public R<User> update(@RequestBody User user){
        log.info("将要修改的user为： {}", user);
        boolean flag = userService.updateById(user);
        if (flag){
            User user1 = userService.getById(user.getId());
            return R.success(user1);
        }
        else
            return R.error(null);
    }
}
